package com.xingfly.inventory.mq;

import com.xingfly.event.CustomRabbitListener;
import com.xingfly.inventory.InventoryRepository;
import com.xingfly.inventory.model.Inventory;
import com.xingfly.order.sdk.command.OrderItemCommand;
import com.xingfly.order.sdk.event.OrderCreatedEvent;
import com.xingfly.product.sdk.event.product.ProductCreatedEvent;
import com.xingfly.product.sdk.event.product.ProductNameUpdatedEvent;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by SuperS on 2019/11/21.
 *
 * @author SuperS
 */
@Component
@CustomRabbitListener
public class InventoryEventHandler {

    private InventoryRepository repository;

    public InventoryEventHandler(InventoryRepository repository) {
        this.repository = repository;
    }

    @RabbitHandler
    public void processProductCreatedEvent(ProductCreatedEvent event) {
        Inventory inventory = Inventory.create(event.getProductId(), event.getName());
        repository.save(inventory);
    }

    @RabbitHandler
    public void processProductNameUpdatedEvent(ProductNameUpdatedEvent event) {
        Inventory inventory = repository.findByProductId(event.getProductId()).
                orElseThrow(() -> new RuntimeException("Inventory Not Found!"));
        inventory.updateProductName(event.getNewName());
        repository.save(inventory);
    }

    @RabbitHandler
    public void processOrderCreatedEvent(OrderCreatedEvent event) {
        List<OrderItemCommand> items = event.getItems();
        items.forEach(item -> {
            Inventory inventory = repository.findByProductId(item.getProductId()).
                    orElseThrow(() -> new RuntimeException("Inventory Not Found!"));
            inventory.decrease(item.getCount());
            repository.save(inventory);
        });
    }
}
